﻿using System.Text;
using RpcHelper;
using RpcModel;
using RpcSync.Collect.Model;
using RpcSync.Model;

namespace RpcSync.Collect.linq
{
    internal static class LinqHelper
    {
        public static void InitConfig(this ConfigItem config)
        {
            if (config.RpcMerId != 0 || config.ServerId != 0)
            {
                config.IsPublic = true;
                if (config.RpcMerId != 0 && config.ServerId != 0)
                {
                    config.Weight = 3;
                }
                else if (config.ServerId != 0)
                {
                    config.Weight = 2;
                }
                else
                {
                    config.Weight = 1;
                }
            }
            config.Key = string.Join("_", config.ServerId, config.RpcMerId, config.Name.Trim().ToLower());
        }
        public static string GetConfigMd5(this SysConfig[] configs)
        {
            if (configs.IsNull())
            {
                return string.Empty;
            }
            long maxTime = configs.Max(c => c.ToUpdateTime).ToLong();
            StringBuilder str = new StringBuilder(configs.Length * 30 + 10);
            configs.ForEach(a =>
            {
                 str.Append(a.Name);
                str.Append(",");
            });
            str.Append(maxTime);
            return str.ToString().GetMd5();
        }
        public static string ToMsgBody(this TcpRemoteMsg msg)
        {
            StringBuilder body = new StringBuilder("{", 300);
            body.Append("\"MsgBody\":");
            body.Append(msg.MsgBody);
            if (msg.Tran != null)
            {
                body.Append(",\"Tran\":");
                body.Append(msg.Tran.ToJson());
            }
            if (msg.Track != null)
            {
                body.Append(",\"Track\":");
                body.Append(msg.Track.ToJson());
            }
            if (msg.Stream != null)
            {
                body.Append(",\"StreamLen\":");
                body.Append(msg.Stream.Length.ToString());
            }
            if (msg.Extend != null && msg.Extend.Count > 0)
            {
                body.Append(",\"Extend\":");
                body.Append(msg.Extend.ToJson());
            }
            body.Append("}");
            return body.ToString();
        }
    }
}
